<template>
  <div class="login-model">
    <div class="mask" @click="close"></div>
    <div class="login-box">
      <img src="../assets/img/close.png" alt="" @click="close" class="close" />
      <ul class="tital">
        <li :class="isShowForm ? 'active' : ''" @click="isShowForm = true">
          手机号码登录
        </li>
        <li style="margin: -2px 10px; cursor: auto">|</li>
        <li :class="!isShowForm ? 'active' : ''" @click="toShowWeixin">
          微信扫描登录
        </li>
      </ul>
      <div class="body">
        <div class="form" v-show="isShowForm">
          <div class="input-group uname">
            <input type="text" placeholder="请输入手机号" v-model="phoneNum" />
          </div>
          <div class="input-group mb20">
            <slide-verify
              :l="42"
              :r="20"
              :w="360"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
            ></slide-verify>
          </div>
          <div class="input-group code mb20">
            <input type="text" placeholder="请输入验证码" v-model="SMScode" />
            <div class="btn" :class="isShowCount ? 'has-count' : ''">
              <span v-show="!isShowCount" @click="getSMScode">
                获取验证码
              </span>
              <span v-show="isShowCount"> {{ count }} S </span>
            </div>
          </div>
          <div class="btn" @click="submitLogin">登录</div>
        </div>
        <div class="wx-qrcode" id="weixin" v-show="!isShowForm">微信二维码</div>
      </div>
    </div>
  </div>
</template>

<script>
import { validataPhoneNumber } from "../utils";
import { mapMutations, mapActions } from "vuex";
import { PhoneLoginAPI, SendSMSAPI, BinPhoneAPI,UserProfilesAPI } from "../request/api";
export default {
  data() {
    return {
      isShowForm: true,
      msg: "向右滑动",
      //手机号码
      phoneNum: "",
      //用户手机验证码
      SMScode: "",
      isShowCount: false,
      count: 60,
    };
  },
  methods: {
    ...mapMutations({
      chenIsShowLoginModel: "showLoginModel/chenIsShowLoginModel",
      chenIsLogined: "loginStatus/chenIsLogined",
    }),
    ...mapActions({
      asyncChenIsShowToast: "showToast/asyncChenIsShowToast",
      asyncChenUserInfo:"userInfo/asyncChenUserInfo"
    }),
    toShowWeixin() {
      this.isShowForm = false;

      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,Lyogd3hsb2dpbi5jc3MgKi8NCi5pbXBvd2VyQm94IC50aXRsZSwgLmltcG93ZXJCb3ggLmluZm97DQogIGRpc3BsYXk6IG5vbmU7DQp9DQoNCi5pbXBvd2VyQm94IC5xcmNvZGV7DQogIG1hcmdpbi10b3A6IDIwcHg7DQp9",
      });
    },
    //定时器倒计时
    countDown() {
      let timer = setInterval(() => {
        this.count--;
        if (this.count === 0) {
          clearInterval(timer);
          this.isShowCount = false;
          this.count = 60;
        }
      }, 1000);
    },
    //封装----判断手机和滑动图有没有完成
    verifyFn() {
      if (!validataPhoneNumber(this.phoneNum)) {
        this.asyncChenIsShowToast({
          msg: "请输入正确的手机号码",
          type: "warning",
        });
        // this.$refs.phone.focus();
        return false;
      }

      //2.验证滑块是否通过
      if (this.msg === "再试一次" || this.msg === "向右滑动") {
        this.asyncChenIsShowToast({
          msg: "请滑动滑块到正确位置",
          type: "warning",
        });
        return false;
      }

      return true;
    },
    async getSMScode() {
      //点击获取短信验证码执行这里的代码
      //调用方法中如果用return需注意方法return后加个false
      if (!this.verifyFn()) {
        return;
      }

      //1.验证用户输入的手机号码格式是否正确
      // if(!正则表达式.test(用户输入的信息)){
      // if (!validataPhoneNumber(this.phoneNum)) {
      //   alert("请输入正确的手机号码");
      //   return;
      // }

      // //2.验证滑块是否通过
      // if (this.msg === "再试一次" || this.msg === "向右滑动") {
      //   alert("请滑动滑块到正确位置!");
      //   return;
      // }

      let res = await SendSMSAPI({
        phone: this.phoneNum.trim(),
      });
      if (res) {
        //请求成功时执行
        this.asyncChenIsShowToast({
          msg: "成功获取验证码",
          type: "success",
        });
        this.isShowCount = true;
        this.countDown();
      }
      //3.倒计时
    },
    //隐藏登录框
    close() {
      this.chenIsShowLoginModel(false);
    },
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    //点击登录按钮执行的代码
    async submitLogin() {
      //1 判断手机号码验证
      //2 判断图片滑块验证码的验证
      /*  if (this.msg === "再试一次" || this.msg === "向右滑动") {
        alert("请滑动滑块到正确位置!");
        return;
      } */
      if (!this.verifyFn()) {
        return;
      }
      if (!this.SMScode) {
        this.asyncChenIsShowToast({
          msg: "请输入验证码",
          type: "warning",
        });
        return;
      }

      //点击登录,发送验证请求
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        //判断有没有uuid,如果有怎么这个号码扫过描,但是没有绑定----所以在发送手机号和验证码的同时还需要uuid,传给后端绑定这个手机微信
        res = await BinPhoneAPI({
          phone: this.phoneNum.trim(),
          verifyCode: this.SMScode.trim(),
          uuid,
        });
      } else {
        //没有uuid直接验证手机号和验证码登录
        res = await PhoneLoginAPI({
          phone: this.phoneNum.trim(),
          verifyCode: this.SMScode.trim(),
        });
      }
      if (!res)return;
        //分析登录成功之后的逻辑
        //1.提示用户登录成功
        this.asyncChenIsShowToast({
          msg: "登录成功",
          type: "success",
        });
        //2.关闭登录窗口
        this.close();
        //3.报错token值到localStorage中
        localStorage.setItem("x-auth-token", res["x-auth-token"]);
        //4.登录状态的转换
        this.chenIsLogined(true);
        //5.删除uuid 并且清除浏览器地址栏是的code
        if(uuid){
        localStorage.removeItem("uuid");
        this.$router.push(this.$route.path)
        }  

        //请求用户信息
        this.asyncChenUserInfo()
    },
  },
};
</script>
 
<style lang = "less" scoped>
@import "../assets/css/global.less";
.login-model {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .login-box {
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    margin: auto;
    .close {
      position: absolute;
      right: 60px;
      top: 15px;
      cursor: pointer;
    }
    .tital {
      cursor: pointer;
      display: flex;
      justify-content: center;
      padding-top: 40px;
      margin-bottom: 30px;
      font-size: 18px;
      color: #ccc;
      .active {
        color: #333;
      }
    }
    .body {
      width: 360px;
      height: 200px;
      margin: 0 auto;

      .form {
        .uname {
          margin-bottom: 5px;
        }
        .input-group {
          display: flex;

          input {
            height: 48px;
            width: 100%;
            text-indent: 10px;
            border: 1px solid #ccc;
          }
        }
        .code input {
          width: 260px;
          margin-right: 8px;
        }
        .code .btn {
          flex: 1;
        }
        .btn {
          height: 50px;
          line-height: 50px;
          background-color: @base-color;
          color: #fff;
          text-align: center;
          cursor: pointer;
        }
        .has-count {
          background-color: #ccc;
        }
      }
    }
  }
}
.wx-qrcode {
  margin-top: -20px;
  display: flex;
  justify-content: center;
}
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>